package com.atguigu.gulimall.order.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.exception.NoStockException;
import com.atguigu.common.to.mq.OrderTo;
import com.atguigu.common.to.mq.SeckillOrderTo;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.order.constant.OrderConstant;
import com.atguigu.gulimall.order.dao.OrderItemDao;
import com.atguigu.gulimall.order.entity.OrderItemEntity;
import com.atguigu.gulimall.order.entity.PaymentInfoEntity;
import com.atguigu.gulimall.order.enume.OrderStatusEnum;
import com.atguigu.gulimall.order.feign.CartFeignService;
import com.atguigu.gulimall.order.feign.MemberFeignService;
import com.atguigu.gulimall.order.feign.ProductFeignService;
import com.atguigu.gulimall.order.feign.WmsFeignService;
import com.atguigu.gulimall.order.interceptor.LoginUserInterceptor;

import com.atguigu.gulimall.order.service.OrderItemService;
import com.atguigu.gulimall.order.service.PaymentInfoService;
import com.atguigu.gulimall.order.to.OrderCreateTo;
import com.atguigu.gulimall.order.vo.*;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;

import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.order.dao.OrderDao;
import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    private ThreadLocal<OrderSubmitVo> confirmVoThreadLocal =new ThreadLocal<>();
@Autowired
    OrderItemService orderItemService;


    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    CartFeignService cartFeignService;
//    因为连个远程调用所以可以使用线程池来进行异步编排功能，增加程序的运行效率
    @Autowired
    ThreadPoolExecutor executor;

//    远程调用库存管理
    @Autowired
    WmsFeignService wmsFeignService;
//   redis
    @Autowired
    RedisTemplate redisTemplate;

//    商品的远程服务
    @Autowired
    ProductFeignService productFeignService;

//    引入消息队列
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    PaymentInfoService paymentInfoService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public OrderConfirmVo confirmOrder() throws ExecutionException, InterruptedException {

        OrderConfirmVo confirmVo =new OrderConfirmVo();

//        从登录拦截器中获取对象方法
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
//        进行异步编排

        CompletableFuture<Void> addressFuture = CompletableFuture.runAsync(() -> {
//            //        1.远程查询查询用户的地址列表
            RequestContextHolder.setRequestAttributes(requestAttributes);
       List<MemberAddressVo> address = memberFeignService.getAddress(memberRespVo.getId());
       confirmVo.setAddress(address);
        }, executor);

        CompletableFuture<Void> cartFuture = CompletableFuture.runAsync(() -> {
            RequestContextHolder.setRequestAttributes(requestAttributes);
            //       2远程查询购物车所有选中的购物项
            List<OrderItemVo> items = cartFeignService.getCurrentUserCartItems();
            confirmVo.setItems(items);
        }, executor).thenRunAsync(()->{
            List<OrderItemVo> items = confirmVo.getItems();
            List<Long> collect = items.stream().map(item -> item.getSkuId()).collect(Collectors.toList());

            R hasStock = wmsFeignService.getSkusHasStock(collect);
        List<SkuStockVo> data=hasStock.getData(new TypeReference<List<SkuStockVo>>(){});
        if(data!=null){
            Map<Long, Boolean> map = data.stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
            confirmVo.setStocks(map);
        }

        },executor);


//        3.查询用户的积分
        Integer integration = memberRespVo.getIntegration();
        confirmVo.setIntegration(integration);

//        4.其他数据在orderConfirmVo中通过get方法自动计算

//        todo 5.防重令牌

        String token = UUID.randomUUID().toString().replace("-", "");
//        给redis服务器一份
        redisTemplate.opsForValue().set(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId(),token,30,TimeUnit.MINUTES);
//        给页面一份
        confirmVo.setOrderToken(token);


//等待线程池都执行完毕
        CompletableFuture.allOf(addressFuture,cartFuture).get();

        return confirmVo;
    }

//    本地事务  在分布式的系统中，只能控制住自己的回滚，控制不了其他服务的回滚
//    分布式事务：最大原因  网络问题+分布式机器
//     @Transactional(isolation = Isolation.REPEATABLE_READ)  //事务的隔离级别 可重复读取多次
//@GlobalTransactional  //这个是seatea的全局事务  高并发场景
    @Transactional //事务的隔离级别 可重复读取多次
    @Override
    public SubmitOrderResponseVo submitOrder(OrderSubmitVo vo) {

        confirmVoThreadLocal.set(vo);

       SubmitOrderResponseVo response =new SubmitOrderResponseVo();

        //        从登录拦截器中获取对象方法
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        response.setCode(0);

        confirmVoThreadLocal.set(vo);

        /*令牌的对比和删除必须保障原子性*/

//        使用脚本
        String script="if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
//        返回0令牌失败 返回1成功
        String orderToken = vo.getOrderToken();
//原子验证令牌和删除令牌
        Long result=(Long) redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId()), orderToken);

        if(result==0L){
            //            失败
            response.setCode(1);
            return response;

        }else{
//            成功
//            //        下单：创建订单，令牌的对比，价格的对比，锁库存
//          1.  创建订单项等信息
            OrderCreateTo order =createOrder();
//            2.验价
            BigDecimal payAmount =order.getOrder().getPayAmount();
            BigDecimal payPrice =vo.getPayPrice();
            if(Math.abs(payAmount.subtract(payPrice).doubleValue())<0.01){
//                金额对比
//                保存订单
                saveOrder(order);
//                4.库存锁定,只要有异常回滚订单数据
//                订单号，所有的订单项（skuId,skuname,num）
                WareSkuLockVo lockVo =new WareSkuLockVo();
                lockVo.setOrderSn(order.getOrder().getOrderSn());
                List<OrderItemVo> locks = order.getOrderItems().stream().map(item -> {
                    OrderItemVo itemVo = new OrderItemVo();
                    itemVo.setSkuId(item.getSkuId());
                    itemVo.setCount(item.getSkuQuantity());
                    itemVo.setTitle(item.getSkuName());
                    return itemVo;
                }).collect(Collectors.toList());
             lockVo.setLocks(locks);
//             远程锁定库存

//                为保障高并发。库存服务自己回滚， 可以发消息给库存服务
//                库存本身也可以使用自动解锁模式  使用消息队列来完成
                R r = wmsFeignService.orderLockStock(lockVo);
                if(r.getCode()==0){
//                    锁定成功
                    response.setOrder(order.getOrder());
                    //                    todo  订单成功发送消息
                    rabbitTemplate.convertAndSend("order-event-exchange","order.create.order",order.getOrder());
                    return response;

                }else{
/*//                    锁定失败
                   //throw new  NoStockException();
                   response.setCode(3);
                    return response;
                    //没办法不可执行*/

//锁定失败
                     String msg =(String)r.get("msg");
                        throw  new NoStockException(msg);






                }

            }else{
                response.setCode(2);
                return response;
            }
        }


//        String redisToken = (String) redisTemplate.opsForValue().get(OrderConstant.USER_ORDER_TOKEN_PREFIX + memberRespVo.getId());
//
//if(orderToken!=null && orderToken.equals(redisToken)){
////    令牌通过
//    redisTemplate.delete(OrderConstant.USER_ORDER_TOKEN_PREFIX+memberRespVo.getId());
//}else{
////    不通过
//}

    }



    @Override
    public void closeOrder(OrderEntity entity) {
//  关闭订单之前
//        查询当前这个订单的最新状态
        OrderEntity orderEntity = this.getById(entity.getId());
        if(orderEntity.getStatus()==OrderStatusEnum.CREATE_NEW.getCode()){
//            关单
            OrderEntity update =new OrderEntity();
            update.setId(entity.getId());
            update.setStatus(OrderStatusEnum.CANCLED.getCode());
            this.updateById(update);
            OrderTo orderTo =new OrderTo();
            BeanUtils.copyProperties(orderEntity,orderTo);
            //发给mq一个
            rabbitTemplate.convertAndSend("order-event-exchange","order.release.other",orderTo);
        }
    }

    @Override
    public OrderEntity getOrderByOrderSn(String orderSn) {
        OrderEntity order_sn = this.getOne(new QueryWrapper<OrderEntity>().eq("order_sn", orderSn));
        return order_sn;
    }

    @Override
    public PayVo getOrderPay(String orderSn) {

        PayVo payVo =new PayVo();
       OrderEntity order= this.getOrderByOrderSn(orderSn);

        BigDecimal bigDecimal = order.getPayAmount().setScale(2, BigDecimal.ROUND_UP);
        payVo.setTotal_amount(bigDecimal.toString());
        payVo.setOut_trade_no(order.getOrderSn());

        List<OrderItemEntity> order_sn = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", orderSn));
        OrderItemEntity itemEntity = order_sn.get(0);



        payVo.setSubject(itemEntity.getSkuName());
        payVo.setBody(itemEntity.getSkuAttrsVals());

        return payVo;




    }

    @Override
    public PageUtils queryPageWithItem(Map<String, Object> params) {

//        通过拦截器 得到
        MemberRespVo memberRespVo = LoginUserInterceptor.loginUser.get();

        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>().getPage(params),
                new QueryWrapper<OrderEntity>()
                .eq("member_id",memberRespVo.getId())
                .orderByDesc("id")
        );

        List<OrderEntity> order_sn = page.getRecords().stream().map(order -> {
            List<OrderItemEntity> itemEntities = orderItemService.list(new QueryWrapper<OrderItemEntity>().eq("order_sn", order.getOrderSn()));
            order.setItemEntities(itemEntities);
            return order;
        }).collect(Collectors.toList());


        page.setRecords(order_sn);
        return new PageUtils(page);
    }
//处理支付宝的结果
    @Override
    public String handlePayResult(PayAsyncVo vo) {
//        1.保存交易流水
        PaymentInfoEntity infoEntity =new PaymentInfoEntity();

        infoEntity.setAlipayTradeNo(vo.getTrade_no());
        infoEntity.setOrderSn(vo.getOut_trade_no());
        infoEntity.setPaymentStatus(vo.getTrade_status());
        infoEntity.setCallbackTime(vo.getNotify_time());

        paymentInfoService.save(infoEntity);

//        修改订单的状态信息
        if(vo.getTrade_status().equals("TRADE_SUCCESS")||vo.getTrade_status().equals("TRADE_FINISHED")){
         String outTradeNo= vo.getOut_trade_no();
         this.baseMapper.updateOrderStatus(outTradeNo,OrderStatusEnum.PAYED.getCode());
        }


        return "success";
    }

    @Override
    public void createSeckillOrder(SeckillOrderTo seckillOrder) {
//        保存订单信息
        OrderEntity orderEntity =new OrderEntity();
        orderEntity.setOrderSn(seckillOrder.getOrderSn());
        orderEntity.setMemberId(seckillOrder.getMemberId());

        orderEntity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
//地址用默认的吧
        //orderEntity.setReceiverDetailAddress();
        BigDecimal multiply = seckillOrder.getSeckillPrice().multiply(new BigDecimal("" + seckillOrder.getNum()));
        orderEntity.setPayAmount(multiply);

        this.save(orderEntity);

//        保存订单项的信息
//        todo 获取当前sku的详细信息进行设置
        OrderItemEntity orderItemEntity =new OrderItemEntity();
        orderItemEntity.setOrderSn(seckillOrder.getOrderSn());
        orderItemEntity.setRealAmount(multiply);
        orderItemEntity.setSkuQuantity(seckillOrder.getNum());


        orderItemService.save(orderItemEntity);
    }

    //保存订单信息
    private void saveOrder(OrderCreateTo order) {
        OrderEntity orderEntity =order.getOrder();
        orderEntity.setModifyTime(new Date());
        this.save(orderEntity);

        List<OrderItemEntity> orderItems = order.getOrderItems();
        orderItemService.saveBatch(orderItems);
    }


    //    创建订单的方法
    private OrderCreateTo createOrder(){

        OrderCreateTo createTo =new OrderCreateTo();
//        1.生成订单号
        String orderSn = IdWorker.getTimeId();
//        2创建订单号
        OrderEntity orderEntity = buildOrder(orderSn);


//        2获取到所有的订单项目
        List<OrderItemEntity> itemEntities = buildOrderItems(orderSn);

//        3.验价 计算价格积分等相关信息
      computePrice(orderEntity,itemEntities);

      createTo.setOrder(orderEntity);
      createTo.setOrderItems(itemEntities);

        return createTo;

    }


//    计算价格相关的验价
    private void computePrice(OrderEntity orderEntity, List<OrderItemEntity> itemEntities) {
        BigDecimal total =new BigDecimal("0.0");
        BigDecimal coupon =new BigDecimal("0.0");
        BigDecimal promotion =new BigDecimal("0.0");
        BigDecimal integration =new BigDecimal("0.0");
        BigDecimal gift =new BigDecimal("0.0");
        BigDecimal growth =new BigDecimal("0.0");


//        订单的总额， 叠加每一个订单想的总额信息
        for(OrderItemEntity entity:itemEntities){
          coupon =coupon.add(entity.getCouponAmount());
          integration=integration.add(entity.getPromotionAmount());
          promotion=promotion.add(entity.getPromotionAmount());
          total=total.add(entity.getRealAmount());

          gift =gift.add(new BigDecimal((entity.getGiftIntegration().toString())));
          growth=growth.add(new BigDecimal(entity.getGiftGrowth().toString()));

        }

//        1.订单价格相关
        orderEntity.setTotalAmount(total);
//        应付总额
        orderEntity.setPayAmount(total.add(orderEntity.getFreightAmount()));
        orderEntity.setPromotionAmount(promotion);
        orderEntity.setIntegrationAmount(integration);
        orderEntity.setCouponAmount(coupon);

//        设置积分等信息
        orderEntity.setIntegration(gift.intValue());
        orderEntity.setGrowth(growth.intValue());
//        订单的删除状态 o是未删除
        orderEntity.setDeleteStatus(0);

    }

    //构建订单的方法
    private OrderEntity buildOrder(String orderSn) {

//        获取会员的对象
        MemberRespVo respVo = LoginUserInterceptor.loginUser.get();

        OrderEntity entity =new OrderEntity();
        entity.setOrderSn(orderSn);
        entity.setMemberId(respVo.getId());

//        获取收货地址
        OrderSubmitVo submitVo = confirmVoThreadLocal.get();
        R fare = wmsFeignService.getFare(submitVo.getAddrId());
        FareVo fareResp = fare.getData(new TypeReference<FareVo>() {
        });

        entity.setFreightAmount(fareResp.getFare());
//        设置收货人信息
        entity.setReceiverCity(fareResp.getAddress().getCity());
        entity.setReceiverDetailAddress(fareResp.getAddress().getDetailAddress());
        entity.setReceiverName(fareResp.getAddress().getName());
        entity.setReceiverPhone(fareResp.getAddress().getPhone());
        entity.setReceiverPostCode(fareResp.getAddress().getPostCode());
        entity.setReceiverProvince(fareResp.getAddress().getProvince());
        entity.setReceiverRegion(fareResp.getAddress().getRegion());

//        设置订单的状态
        entity.setStatus(OrderStatusEnum.CREATE_NEW.getCode());
        entity.setAutoConfirmDay(7);

        return entity;
    }

    //构建所有订单想数据
    private List<OrderItemEntity> buildOrderItems(String orderSn) {
//        最后确定购物项额价格
        List<OrderItemVo> currentUserCartItems = cartFeignService.getCurrentUserCartItems();
        if(currentUserCartItems!=null && currentUserCartItems.size()>0){
            List<OrderItemEntity> itemEntities = currentUserCartItems.stream().map(cartItem -> {
//                构建订单数据
                OrderItemEntity itemEntity = buildOrderItem(cartItem);
                itemEntity.setOrderSn(orderSn);

                return itemEntity;
            }).collect(Collectors.toList());
            return itemEntities;
        }
        return null;

    }

//    构建每一个订单想木
    private OrderItemEntity buildOrderItem(OrderItemVo cartItem) {
        OrderItemEntity itemEntity =new OrderItemEntity();
//        1.订单信息，订单号 在builderItems中 已经做啦
//        2.spu
      Long skuId= cartItem.getSkuId();
        R r = productFeignService.getSpuInfoBySkuId(skuId);
        SpuInfoVo data = r.getData(new TypeReference<SpuInfoVo>() {
        });
        itemEntity.setSpuId(data.getId());
        itemEntity.setSpuBrand(data.getBrandId().toString());
        itemEntity.setSpuName(data.getSpuName());
        itemEntity.setCategoryId(data.getCatalogId());

//        3.sku

        itemEntity.setSkuId(cartItem.getSkuId());
        itemEntity.setSkuName(cartItem.getTitle());
        itemEntity.setSkuPic(cartItem.getImage());
        itemEntity.setSkuPrice(cartItem.getPrice());
       String skuAttr= StringUtils.collectionToDelimitedString(cartItem.getSkuAttr(),";");
       itemEntity.setSkuQuantity(cartItem.getCount());


//        4.积分信息
        itemEntity.setGiftGrowth(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());
        itemEntity.setGiftIntegration(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount().toString())).intValue());

//        5.订单想的价格信息
        itemEntity.setPromotionAmount(new BigDecimal("0"));
        itemEntity.setCouponAmount(new BigDecimal("0"));
        itemEntity.setIntegrationAmount(new BigDecimal("0"));

        BigDecimal orign = itemEntity.getSkuPrice().multiply(new BigDecimal(itemEntity.getSkuQuantity().toString()));
        BigDecimal subtract =orign.subtract(itemEntity.getCouponAmount())
                                  .subtract(itemEntity.getPromotionAmount())
                                  .subtract(itemEntity.getIntegrationAmount());
        itemEntity.setRealAmount(subtract);

        return itemEntity;
    }

}
